package com.jzlin.alltools.controller;

import com.jzlin.alltools.controller.req.ChatSseReq;
import com.jzlin.alltools.core.http.RestRet;
import com.jzlin.alltools.core.sse.SseClient;
import com.jzlin.alltools.service.chatai.support.BaseChatMessage;
import com.jzlin.alltools.service.chatai.support.ChatExecutor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * AI大模型问答控制器.
 *
 * @author Lin
 * @date 2024/10/9
 */
@Api(tags = {"AI问答"})
@RestController
@RequestMapping("/chat")
public class ChatAiController {

    @Autowired
    private ChatExecutor chatExecutor;

    @ApiOperation("流式问答")
    @PostMapping(path = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter sseChat(@RequestBody ChatSseReq req) {
        // sseId
        String sseId = SseClient.createSseId();
        SseEmitter sseEmitter = SseClient.createSse(sseId);

        // 构建消息对象
        BaseChatMessage baseChatMessage = BaseChatMessage.builder()
                .sseId(sseId)
                .sessionId(req.getSessionId())
                .message(req.getMessage())
                .config(req.getConfig()).build();
        //发送信息至会话线程池
        chatExecutor.executeMessage(baseChatMessage);

        return sseEmitter;
    }

    @ApiOperation("新建会话")
    @PostMapping(path = "/session/create")
    public RestRet<String> createSession() {
        return RestRet.createSuccessRet(SseClient.createSseId());
    }
}
